package com.bitoon.basketdudes.web.interceptors;

import com.bitoon.basketdudes.web.jpa.Usuario;
 
import com.opensymphony.xwork2.*;
import com.opensymphony.xwork2.interceptor.Interceptor;
import java.io.*;
import java.util.*;

import org.apache.log4j.Logger;

public class FormatJSON implements Interceptor {

    private Logger log = Logger.getLogger(FormatJSON.class);

    public void destroy() {
    }

    public void init() {
    }

    public String intercept(ActionInvocation actionInvocation) throws Exception {
        String result = null;
        try {
            log.debug("Interceptando antes en FormatJSON");
            result = actionInvocation.invoke();

            log.debug("En FormatJSON: " + actionInvocation.getResultCode());
        } catch (Exception e) {
            log.error("Error en FormatJSON", e);
        }

        return result;
    }

    private boolean estaLogado(Map session) {
        boolean retorno = false;
        log.debug("interceptor [1]");
        if (session.containsKey("bd_userId")) {
            if ( (Integer.parseInt((String)session.get("bd_userId"))) > 0) {
                retorno = true;
                log.debug("interceptor [2]");
            }
        }

        return retorno;
    }

    private String dameIdUsuarioLogado(Map session) {
        String retorno = "";

        if (session.containsKey("bd_userId")) {
            retorno = (String)session.get("bd_userId");
        } else {
            retorno = "0";
        }

        return retorno;
    }

    private Usuario dameUsuarioLogado(Map session) {
        Usuario retorno = null;

        if (session.containsKey("bd_userLogado")) {
            retorno = (Usuario)session.get("bd_userLogado");

            FileOutputStream fos = null;
            ObjectOutputStream out = null;
            try {

                File file = new File("/home/webdev/outsize.txt");
                fos = new FileOutputStream(file);
                out = new ObjectOutputStream(fos);
                out.writeObject(retorno);
                out.close();

            } catch (Exception e) {
                log.error("Error: " + e);
            }

        } 

        return retorno;
    }

}
